package com.axujie.tlgypt.service.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static BasicDataSource dataSource;
	private static ThreadLocal<Connection> threadLocal;
	static{
		try{
			String configPath = DBUtil.class.getResource("/").getFile()+"dataBase.properties";
			Properties prop = new Properties();
			InputStream is = new FileInputStream(new File(configPath));
			prop.load(is);
			is.close();
			dataSource = new BasicDataSource();
			dataSource.setDriverClassName(prop.getProperty("driver").trim());
			dataSource.setUrl(prop.getProperty("url").trim());
			dataSource.setUsername(prop.getProperty("user").trim());
			dataSource.setPassword(prop.getProperty("password").trim());
			dataSource.setInitialSize(Integer.parseInt(prop.getProperty("initSize")));
			dataSource.setMaxActive(Integer.parseInt(prop.getProperty("maxSize")));
			threadLocal = new ThreadLocal<Connection>();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 获取连接
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception{
			Connection conn = dataSource.getConnection();
			threadLocal.set(conn);
			return conn;
	}
	/**
	 * 关闭连接
	 */
	public static void closeConnection() {
		try{
			Connection conn = threadLocal.get();
			if(conn!=null){
				conn.close();
				threadLocal.remove();
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		}
	}
	
	/**
	 * 释放资源
	 * @param resultSet
	 * @param statement
	 * @param connection
	 */
	public static void closeResource(ResultSet resultSet,Statement statement,Connection connection) {
		if(resultSet!=null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(statement!=null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(connection!=null) {
			closeConnection();
		}
	}
}
